import threading
import socket
import time


class mainThread(threading.Thread):
    def __init__(self, conf):
        threading.Thread.__init__(self)
        self.conf = conf
        self.host = "192.168.31.211"
        self.port = 8010
        self.web = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.guid = ""
        self.isRun = True

    def stop(self):
        self.isRun = False
        self.web.close()

    def do_Send(self, text):
        text["guid"] = self.guid
        if self.isRun:
            self.web.send(f"{text}".encode("utf-8"))

    def do_QueueSend(self):
        """发送队列消息"""
        while self.isRun:
            time.sleep(0.1)
            if not self.conf[4].empty():
                msg = self.conf[4].get()
                self.do_Send(msg)

    def run(self):
        print("开始网络线程...")
        buff = 512
        self.web.connect((self.host, self.port))
        threading.Thread(target=self.do_QueueSend).start()
        while self.isRun:
            time.sleep(0.1)
            try:
                s = self.web.recv(buff)
                if not s:
                    break
                self.msgManager(s.decode("utf-8"))
            except BaseException as err:
                print("ERR:", err)
                break
        print("结束网络线程...")

    def msgManager(self, msg):
        """消息接收管理器"""
        try:
            data = eval(msg)
        except BaseException as err:
            print(f"解码消息失败, 游戏终止. {err}")
            self.stop()
        # --------------------- 初始化消息 ------------------------- #
        if data.get("act") == "init":
            self.guid = data.get("guid")
            self.conf[0] = "wait"
            self.conf[1] = [
                data.get("msg"),
                "1  准备就绪",
            ]
        # --------------------- 公共消息 --------------------------- #
        guid = data.get("guid")
        if not guid == self.guid:
            self.newsManager(data)
            return
        # -------------------- 私有消息 ---------------------------- #
        if data.get("act") == "wait":
            self.conf[0] = "wait"
            self.conf[1] = ["战前准备，等待就绪.", "1 准备就绪"]
        elif data.get("act") == "ready":
            self.conf[0] = "ready"
            self.conf[1] = ["准备就绪,等待进入战场.", "1 取消准备"]

    def newsManager(self, data):
        """公共消息管理器"""
        # print("公共消息:", data)
        if data.get("act") == "lock":
            self.conf[0] = "lock"
            self.conf[1] = [f'开始倒计时: {data.get("data")}']
        elif data.get("act") == "fight":
            self.conf[0] = "fight"
            self.conf[1] = None
        elif data.get("act") == "gens":
            self.conf[3].put(data)
        else:
            pass
